package com.xxh.securitydemo.service.impl;

import com.xxh.securitydemo.dao.UmsAdminDao;
import com.xxh.securitydemo.dao.UmsMenuDao;
import com.xxh.securitydemo.dto.UmsMenuNode;
import com.xxh.securitydemo.model.UmsAdmin;
import com.xxh.securitydemo.model.UmsMenu;
import com.xxh.securitydemo.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    UmsMenuDao umsMenuDao;


    /***
     *
     * @return 返回树状的菜单。
     */
    @Override
    public List<UmsMenuNode> treeList() {
        List<UmsMenu> menus = umsMenuDao.selectList(null);

        List<UmsMenuNode> list = menus.stream()
                .filter(umsMenu -> umsMenu.getParentId() == 0)
                .map(umsMenu -> CovenTreeNode(umsMenu, menus))
                .collect(Collectors.toList());
        return list;
    }
    //获取父菜单的子菜单
    private UmsMenuNode CovenTreeNode(UmsMenu parent,List<UmsMenu> all){

        List<UmsMenuNode> childNodes = all.stream().filter(umsMenu -> {
            return umsMenu.getParentId().equals(parent.getId());
        }).map(umsMenu -> {
            UmsMenuNode childNode = new UmsMenuNode();
            BeanUtils.copyProperties(umsMenu, childNode);
            return childNode;
        }).collect(Collectors.toList());
        UmsMenuNode parentNode = new UmsMenuNode();
        BeanUtils.copyProperties(parent,parentNode);
        parentNode.setChild(childNodes);
        return parentNode;
    }
}
